package online.heycm.codegenerator.generator;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

/**
 * MyBatisPlus 代码生成器
 *
 * @author heycm
 * @since 2023/12/17 14:47
 */
@Slf4j
public class MyBatisPlusGenerator {

    public static boolean generate(GeneratorSetting setting) {
        try {
            FastAutoGenerator.create(setting.getUrl(), setting.getUsername(), setting.getPassword())
                    .globalConfig(builder -> {
                        // 作者
                        builder.author(setting.getAuthor());
                        // 生成文件输出目录
                        builder.outputDir(setting.getOutput());
                        // 启用 Swagger
                        if (setting.isEnableSwagger()) {
                            builder.enableSwagger();
                        }
                        // 禁止自动打开目录
                        builder.disableOpenDir();
                        // 日期类型设置为Date，默认LocalDateTime
                        builder.dateType(DateType.ONLY_DATE);
                    })
                    .packageConfig(builder -> {
                        // 设置父包名
                        builder.parent(setting.getParentPackage());
                        // 设置父包模块名
                        // builder.moduleName("system")
                        // 生成路径
                        String output = setting.getOutput() + GeneratorHelper.packageToPath(setting.getParentPackage());
                        Map<OutputFile, String> pathInfo = new HashMap<>();
                        pathInfo.put(OutputFile.parent, output);
                        pathInfo.put(OutputFile.entity, output);
                        pathInfo.put(OutputFile.controller, output);
                        pathInfo.put(OutputFile.service, output);
                        pathInfo.put(OutputFile.serviceImpl, output);
                        pathInfo.put(OutputFile.mapper, output);
                        pathInfo.put(OutputFile.xml, output);
                        builder.pathInfo(pathInfo);
                    })
                    .strategyConfig(builder -> {
                        // 新生成文件覆盖
                        builder.controllerBuilder().enableFileOverride();
                        builder.serviceBuilder().enableFileOverride();
                        builder.mapperBuilder().enableFileOverride();
                        builder.entityBuilder().enableFileOverride();
                        // Rest 风格
                        builder.controllerBuilder().enableRestStyle();
                        // 下划线转驼峰
                        builder.entityBuilder().naming(NamingStrategy.underline_to_camel);
                        builder.entityBuilder().columnNaming(NamingStrategy.underline_to_camel);
                        // 启用 Lombok
                        if (setting.isEnableLombok()) {
                            builder.entityBuilder().enableLombok();
                        }
                        // 设置生成表
                        builder.addInclude(setting.getTables());
                        // 表名前缀
                        if (!CollectionUtils.isEmpty(setting.getTablePrefixList())) {
                            builder.addTablePrefix(setting.getTablePrefixList());
                        }
                        // 字段前缀
                        if (!CollectionUtils.isEmpty(setting.getFieldPrefixList())) {
                            builder.addFieldPrefix(setting.getFieldPrefixList());
                        }
                        // 自动填充
                        if (!CollectionUtils.isEmpty(setting.getInsertUpdateFills())) {
                            for (String column : setting.getInsertUpdateFills()) {
                                builder.entityBuilder().addTableFills(new Column(column, FieldFill.INSERT_UPDATE));
                            }
                        }
                        if (!CollectionUtils.isEmpty(setting.getInsertFills())) {
                            for (String column : setting.getInsertFills()) {
                                builder.entityBuilder().addTableFills(new Column(column, FieldFill.INSERT));
                            }
                        }
                        if (!CollectionUtils.isEmpty(setting.getUpdateFills())) {
                            for (String column : setting.getUpdateFills()) {
                                builder.entityBuilder().addTableFills(new Column(column, FieldFill.UPDATE));
                            }
                        }
                    })
                    // 使用Freemarker引擎模板，默认的是Velocity引擎模板
                    .templateEngine(new FreemarkerTemplateEngine())
                    .execute();
            return true;
        } catch (Exception e) {
            log.error("MyBatis Plus 代码生成器执行异常", e);
        }
        return false;
    }

    public static void main(String[] args) {
        GeneratorSetting setting = new GeneratorSetting();
        setting.setUrl(
                "jdbc:mysql://localhost:3306/yizhou?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC");
        setting.setUsername("root");
        setting.setPassword("root123");
        ArrayList<String> tables = new ArrayList<>();
        tables.add("pay_account");
        setting.setTables(tables);

        setting.setParentPackage("com.weiwei.code");
        setting.setAuthor("这个是作者");
        setting.setOutput("C:\\Users\\hey\\Desktop\\code-generator");

        generate(setting);
    }
}
